//
//  BBImagePickHandle.m
//  UILbrary
//
//  Created by Apple on 2023/3/3.
//  Copyright © 2023 mac. All rights reserved.
//

#import "BBImagePickHandle.h"

@import PhotosUI;



@interface BBImagePickHandle()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,PHPickerViewControllerDelegate>

@end

@implementation BBImagePickHandle(Tool)

+ (CGSize)screenSize
{
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat width = screenSize.width * scale;
    CGFloat height = screenSize.height * scale;
    return CGSizeMake(width, height);
}

+ (CGSize)targetSize:(PHAsset *)asset
{
    if(!asset){
        return [self screenSize];
    }
    
    CGFloat screen_width = [UIScreen mainScreen].bounds.size.width;
    CGFloat aspectRatio = asset.pixelWidth / (CGFloat)asset.pixelHeight;
    CGFloat pixelWidth = screen_width * [UIScreen mainScreen].scale;
    // 超宽图片
    if(aspectRatio > 1.8){
        pixelWidth = pixelWidth * aspectRatio;
    }
    // 超高图片
    if(aspectRatio < 0.2){
        pixelWidth = pixelWidth *0.5;
    }
    CGFloat pixelHeight = pixelWidth / aspectRatio;
    CGSize size = CGSizeMake(pixelWidth, pixelHeight);
    return size;
}

@end

@implementation BBImagePickHandle

//MARK: - system

- (void)dealloc
{
//    NSLog(@"%s_%@",__func__,self);
}

static  BBImagePickHandle *imagePickHandle = nil;


- (instancetype)init
{
    self = [super init];
    if(self){
        [self p_initConfig];
//        NSLog(@"%s_%@",__func__,self);
    }
    return self;
}


//MARK: - public

- (void)presentPickViewContoller
{
    if (@available(iOS 14, *)) {
        [self handlePHPickerViewController];
    } else {
        [self handleUIImagePickerController];
    }

//    NSLog(@"presentPickViewContoller");
}

//MARK: - private

- (void)p_initConfig
{
    imagePickHandle = self;
}

- (void)p_freeConfig
{
    imagePickHandle = nil;
}

- (void)p_showImgTooBig
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示"
                                                                     message:@"选择图片过大"
                                                              preferredStyle:UIAlertControllerStyleAlert];
    [self.vc presentViewController:alertVC animated:YES completion:nil];
}

- (void)p_finishPick:(UIImage *)image
{
    if(!image){
        [self p_freeConfig];
        return;
    }
    
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
    CGFloat imgSize = imgData.length / 1024 / 1024;
    
//    NSLog(@"imgData = %f",imgSize);
//    NSLog(@"img = %@",image);
    if(imgSize > 20){
        [self p_showImgTooBig];
        [self p_freeConfig];
        return;
    }

    
    if(!self.delegate ||
       ![self.delegate respondsToSelector:@selector(picker:didFinishPicking:)]){
        [self p_freeConfig];
        return;
    }
    
    [self.delegate picker:self didFinishPicking:image];
    [self p_freeConfig];
}

//MARK: - UIImagePickerController

- (void)handleUIImagePickerController
{
    UIImagePickerController *vc = [UIImagePickerController new];
//    vc.allowsEditing = YES;
    vc.delegate = self;
    vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;

    [self.vc presentViewController:vc animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<UIImagePickerControllerInfoKey, id> *)editingInfo
{
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info
{
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    
}

//MARK: - PHPickerViewController

- (void)handlePHPickerViewController
{
    if (@available(iOS 14, *)){
        PHPhotoLibrary *photoLibrary = [PHPhotoLibrary sharedPhotoLibrary];
        PHPickerConfiguration *configuration = [[PHPickerConfiguration alloc] initWithPhotoLibrary:photoLibrary];
        configuration.filter = [PHPickerFilter imagesFilter];
        configuration.preferredAssetRepresentationMode = PHPickerConfigurationAssetRepresentationModeCurrent;
        if (@available(iOS 15, *)) {
            configuration.selection = PHPickerConfigurationSelectionOrdered;
        }
        configuration.selectionLimit = 1;
        // 设置之前选择的 图片
    //    configuration.preselectedAssetIdentifiers =
        PHPickerViewController *pickVc = [[PHPickerViewController alloc] initWithConfiguration:configuration];
        pickVc.delegate = self;

        [self.vc presentViewController:pickVc animated:YES
                         completion:nil];
    }
}

- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results
API_AVAILABLE(ios(14))
{
    [picker dismissViewControllerAnimated:YES completion:nil];

    PHPickerResult *pickResult = results.firstObject;
    NSString *imgId = pickResult.assetIdentifier;
    
    PHFetchResult<PHAsset *> * result = [PHAsset fetchAssetsWithLocalIdentifiers:@[imgId] options:nil];
    PHAsset *asset = result.firstObject;
    
    if(!asset) return;

    CGSize size = [BBImagePickHandle targetSize:asset];
    PHImageRequestOptions *option = [PHImageRequestOptions new];
    option.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    [[PHImageManager defaultManager] requestImageForAsset:asset
                                               targetSize:size
                                              contentMode:PHImageContentModeAspectFill
                                                  options:option
                                            resultHandler:
     ^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        [self p_finishPick:result];
    }];
}


@end
